package com.qf.myshop.dao.impl;

import com.qf.myshop.dao.CartDAO;
import com.qf.myshop.entity.Cart;
import com.qf.myshop.entity.Product;
import com.qf.myshop.utils.DruidUtils;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CartDAOImpl implements CartDAO {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
    private Map<String, String> map = new HashMap<>();
    {
        map.put("c_id", "cid");
        map.put("u_id", "uid");
        map.put("p_id", "pid");
        map.put("c_count", "ccount");
        map.put("c_num", "cnum");

    }
    private Map<String, String> map1 = new HashMap<>();
    {
        map1.put("p_id", "pid");
        map1.put("t_id", "tid");
        map1.put("p_name", "pname");
        map1.put("p_time", "ptime");
        map1.put("p_image", "pimage");
        map1.put("p_price", "pprice");
        map1.put("p_state", "ustate");
        map1.put("p_info", "pinfo");
    }
    @Override
    public List<Cart> list(Integer uid) {
        String sql = "select * from cart where u_id =?";
        try {
           return qr.query(sql,new BeanListHandler<Cart>(Cart.class,new BasicRowProcessor(new BeanProcessor(map))),uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Product findProductBypid(int pid) {
        String sql = "select * from product where p_id =?";
        try {
            return qr.query(sql,new BeanHandler<Product>(Product.class,new BasicRowProcessor(new BeanProcessor(map1))),pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean delByCid(Integer cid) {
        String sql = "delete from cart where c_id =?";
        try {
            return qr.update(sql,cid)>0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean delByUid(Integer uid) {
        String sql = "delete from cart where u_id =?";
        try {
            return qr.update(sql,uid)>0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean updateByCid(Integer cid, Integer cnum, Double count) {
        String sql = "update cart set c_num = ? ,c_count =? where c_id =?";
        try {
            return qr.update(sql,cnum,count,cid)>0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
